package com.wiegand.gui.text.effects {
	import flash.text.TextFormat;	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	/**
	 * @author wie-gand
	 */
	
	public class DecodingTextField extends TextField{

		private var _timer : Timer;
		private var _position : int = 0;
		private var _delay : int = 30;				
		private var _text : String = "";
		private var _keepSpaces : Boolean = false;
		private var _textformat : TextFormat;

		public function DecodingTextField() : void{
			
			super();
			
			_timer = new Timer( _delay );
			
			_timer.addEventListener( TimerEvent.TIMER, timerHandler );
			
		}

		public function get delay() : int{
			
			return _delay;
		}
		
		public function set delay( value : int ) : void{
			
			_delay = value;
		
		}

		override public function getTextFormat ( beginIndex : int = -1, endIndex : int = -1 ) : TextFormat{
			
			beginIndex;
			endIndex;		
			
			return _textformat;
			
		}

		override public function setTextFormat ( format : TextFormat, beginIndex : int = -1, endIndex : int = -1 ) : void{
			
			beginIndex;
			endIndex;
			
			super.setTextFormat( format );
			
			_textformat = format;
			
		}

		override public function get text() : String{
			
			return _text;
			
		}
		
		override public function set text( value : String ) : void{
			
			_text = value;
			
			super.text = this.randomChars( value );
			
			_position = 0;
			
			if( value.length > 0 ){
				
				_timer.delay = _delay;
				
				_timer.start();
			}
		}
				
		public function get keepSpaces() : Boolean{
			
			return _keepSpaces;
		
		}
		
		public function set keepSpaces( value : Boolean ) : void{
			
			_keepSpaces = value;
		
		}
		
		private function timerHandler( e : TimerEvent ) : void{

			_timer.delay = _delay;
			
			_position++;
			
			if( _position > _text.length ){
				
				_timer.stop();
				
				dispatchEvent( new Event( Event.COMPLETE ) );
				
				return;
			}
			
			super.text = _text.substr( 0, _position ) + randomChars( _text.substr( _position ) );
			
			if( _textformat != null ) super.setTextFormat( _textformat );
		
		}
		
		private function randomChars( value : String ) : String{ 
			
			var result:String = "";
			
			var count:int = value.length;
			
			for( var i : int = 0; i < count; i++ ){

				if( keepSpaces && value.charAt( i ) == " "){
					
					result += " ";
				
				}
				else{
					
					result += String.fromCharCode( int( 33 + Math.random() * 93 ) );
				
				}
			}
			
			return result;
		
		}

	}

}